package com.dhcc.httpserver;

import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import com.dhcc.httpserver.configread.Entity;
import com.dhcc.httpserver.configread.Mapping;
import com.dhcc.httpserver.configread.WebHandler;

public class WebApp {

	private static ServletContext context;

	static {
		
		context = new ServletContext();

		try {
			
			SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
			SAXParser saxParser = saxParserFactory.newSAXParser();

			WebHandler webHandler = new WebHandler();

			saxParser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("web.xml"), webHandler);

			Map<String, String> servlet = context.getServlet();
			for (Entity entity : webHandler.getEntityList()) {

				servlet.put(entity.getName(), entity.getClazz());
			}

//			Map<String, String> mapping = context.getMapping();
//			for (Mapping urls_name : webHandler.getMappingList()) {
//				for (String  url : urls_name.getUrlPattern()) {
//					mapping.put(url,urls_name.getName());
//				}
//			
//			}
			Map<String, String> mapping = context.getMapping();
			for (Mapping mapp : webHandler.getMappingList()) {
				List<String> urls = mapp.getUrlPattern();
				for (String url:urls) {
					mapping.put(url, mapp.getName());
				}
				
				
			}
			

		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	public static Servlet getServlet(String url)
			throws InstantiationException, IllegalAccessException, ClassNotFoundException {

		if (url == null || url.trim().equals("")) {
			return null;
		}
		String name = context.getMapping().get(url);
		if (name == null) {
			return null;
		}

		String servlet = context.getServlet().get(name);
		Class clazz = Class.forName(servlet);

		return (Servlet) clazz.newInstance(); // 空构造
	}

}
